﻿using BonjourQuotation.ObjectModel.AccountData;
using BonjourQuotation.ObjectModel.VendorData;
using BonjourQuotation.ObjectModel.LoggerData;
using BonjourQuotation.UI.Models.AccountModel;
using BonjourQuotation.UI.Models.VendorModel;
using BonjourQuotation.UI.Models.PartialModel;
using BonjourQuotation.UI.Models.ReportModel;
using BonjourQuotation.UI.ServiceManagers;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Microsoft.Reporting.WebForms;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using BonjourQuotation.UI.Models.Shared;


namespace BonjourQuotation.UI.Controllers
{
    public class VendorController : BaseController
    {
        VendorManager VenManager;
        private readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        [Authorize]
        [HttpGet]
        public ActionResult ManageVendors()
        {
            VenManager = new VendorManager();
            var ManageVendorsData = VenManager.GetAllVendors(0);
            var ManageVendorsViewModel = InitManageVendorsSearchParams(ManageVendorsData);
            this.SetPermission(ManageVendorsViewModel, AllPermVModel);
            return View("ManageVendors", ManageVendorsViewModel);
        }
        [Authorize]
        [HttpPost]
        public PartialViewResult LoadVendorsGrid(ManageVendorsGridViewModel model)
        {
            VenManager = new VendorManager();
            ManageVendorsGridBData ManageVendorsData = null;
            if (model.IsSearch)
            {
                ManageVendorsGridBData SearchVendorsData = new ManageVendorsGridBData();
                SearchVendorsData = InitSearchVendor(model);
                ManageVendorsData = VenManager.GetSearchedVendors(SearchVendorsData);
            }
            else
                ManageVendorsData = VenManager.GetAllVendors(model.PageNum);
            var ManageVendorsViewModel = InitManageVendorsVModel(ManageVendorsData, model.PageNum);
            ManageVendorsViewModel.TopScrollPossition = model.TopScrollPossition;
            this.SetPermission(ManageVendorsViewModel, AllPermVModel);
            return PartialView("LoadVendorsGrid", ManageVendorsViewModel);
        }
        [Authorize]
        [HttpPost]
        public PartialViewResult AddNewVendorContract(ManageVendorContractsGridViewModel model)
        {
            VenManager = new VendorManager();
            var VendorContract = InitVendorContractsAddBData(model);
            var CreateError = VenManager.CreateVendorContract(VendorContract);
            MessageBoxViewModel MessBoxforCreate = new MessageBoxViewModel()
            {
                Message = CreateError.Message != null ? "Error - Vendor contract seasons must be different:" : "",
            };
            return PartialView("MessageBox", MessBoxforCreate);
        }
        [Authorize]
        [HttpPost]
        public PartialViewResult AddNewVendorContractDetail(ManageVendorContractDetailsGridViewModel model)
        {
            VenManager = new VendorManager();
            var VendorContractDetail = InitVendorContractDetailsAddBData(model);
            var CreateError = VenManager.CreateVendorContractDetail(VendorContractDetail);
            MessageBoxViewModel MessBoxforCreate = new MessageBoxViewModel()
            {
                Message = CreateError.Message != null ? "Error - Vendor contract seasons must be different:" : "",
            };
            return PartialView("MessageBox", MessBoxforCreate);
        }
        [Authorize]
        [HttpGet]
        public PartialViewResult LoadVendorDetails(int VendorID)
        {
            VenManager = new VendorManager();
            var VendorDetData = VenManager.GetVendorDetailsByID(VendorID);
            ModelState.Clear();
            var VendorDetViewModel = InitVendorDetailsViewModel(VendorDetData);
            this.SetPermission(VendorDetViewModel, AllPermVModel);
            if (VendorID == 0)
                VendorDetViewModel.Active = true;
            return PartialView("LoadVendorDetailsGrid", VendorDetViewModel);
        }
        [Authorize]
        [HttpGet]
        public PartialViewResult LoadVendorContracts(int VendorID)
        {
            VenManager = new VendorManager();
            var VendorDetData = VenManager.GetVendorContractsByID(VendorID);
            var VendorDetViewModel = InitVendorContractsViewModel(VendorDetData, VendorID);
            this.SetPermission(VendorDetViewModel, AllPermVModel);
            return PartialView("LoadVendorContractsGrid", VendorDetViewModel);
        }
        [Authorize]
        [HttpGet]
        public PartialViewResult LoadVendorGroups(int VendorID)
        {
            VenManager = new VendorManager();
            var VendorDetData = VenManager.GetVendorGroupsByID(VendorID);
            return PartialView("LoadVendorGroupsGrid", InitVendorGroupsViewModel(VendorDetData));
        }
        [Authorize]
        [HttpGet]
        public PartialViewResult LoadVendorContractDetails(int VendorID, int SeasonID)
        {
            VenManager = new VendorManager();
            var VendorDetData = VenManager.GetVendorContractDetailsByID(VendorID, SeasonID);
            var VendorDetViewModel = InitVendorContractDetailsViewModel(VendorDetData);
            this.SetPermission(VendorDetViewModel, AllPermVModel);
            return PartialView("LoadVendorContractDetailsGrid", VendorDetViewModel);
        }
        [Authorize]
        [HttpPost]
        public PartialViewResult SaveVendorDetailData(VendorDetailsViewModel model)
        {
            VenManager = new VendorManager();
            var VendorData = InitVendorDetailsBData(model);
            if (model.VendorID == 0)
            {
                var CreateError = VenManager.CreateVendor(VendorData);
                MessageBoxViewModel MessBoxforCreate = new MessageBoxViewModel()
                {
                    Message = CreateError.Message != null ? "Error - " + CreateError.Message : "",
                };
                return PartialView("MessageBox", MessBoxforCreate);
            }
            var EditError = VenManager.PostVendorDetailsData(VendorData);
            MessageBoxViewModel MessBoxforEdit = new MessageBoxViewModel()
            {
                Message = EditError.Message != null ? "Error - " + EditError.Message : "",
            };
            return PartialView("MessageBox", MessBoxforEdit);
        }
        [Authorize]
        [HttpPost]
        public PartialViewResult SaveVendorContractsData(ManageVendorContractsGridViewModel model)
        {
            VenManager = new VendorManager();
            var VendorContract = InitVendorContractsBData(model.Row, model.VendorID);
            List<int> SeasonID = new List<int>();
            foreach (var seasonids in VendorContract)
            {
                SeasonID.Add(seasonids.SelectedSeasonID);
                if (SeasonID.Distinct().Count() != SeasonID.Count)
                {
                    MessageBoxViewModel MessBoxforDuplicate = new MessageBoxViewModel()
                    {
                        Message = "Error - Vendor contract seasons must be different:",
                    };
                    return PartialView("MessageBox", MessBoxforDuplicate);
                }
            }

            var EditError = VenManager.PostVendorContractsData(VendorContract, model.VendorID);

            MessageBoxViewModel MessBoxforEdit = new MessageBoxViewModel()
            {
                Message = EditError.Message != null ? "Error - Vendor contract seasons must be different:" + EditError.Message : "",
            };
            return PartialView("MessageBox", MessBoxforEdit);
        }
        [Authorize]
        [HttpPost]
        public PartialViewResult SaveVendorGridData(ManageVendorsGridViewModel model)
        {
            VenManager = new VendorManager();
            var VendorData = InitManageVendorsGridBData(model);
            var EditError = VenManager.SaveVendorsGridData(VendorData);
            MessageBoxViewModel MessBoxforEdit = new MessageBoxViewModel()
            {
                Message = EditError.Message != null ? "Error - " + EditError.Message : "",
            };
            return PartialView("MessageBox", MessBoxforEdit);
        }
        [Authorize]
        [HttpPost]
        public PartialViewResult SaveVendorContractDetailsData(ManageVendorContractDetailsGridViewModel model)
        {
            if (System.Web.HttpContext.Current.Request.Files.Count > 0)
            {
                HttpPostedFile file = System.Web.HttpContext.Current.Request.Files[0];
            }
            VenManager = new VendorManager();
            var VendorContractDetails = InitVendorContractDetailsBData(model);
            var EditError = VenManager.PostVendorContractDetailsData(VendorContractDetails);
            MessageBoxViewModel MessBoxforEdit = new MessageBoxViewModel()
            {
                Message = EditError.Message != null ? "Error - Vendor contract seasons must be different:" : "",
            };
            return PartialView("MessageBox", MessBoxforEdit);
        }
        [Authorize]
        [HttpPost]
        public ActionResult UploadVendorContractFile(string VendorID, string SeasonID)
        {
            VenManager = new VendorManager();
            bool isUploaded = false;
            string message = "File upload failed";
            if(Request.Files.Count == 1)
            {
                var myFile = Request.Files[0];

                if (myFile != null && myFile.ContentLength != 0)
                {
                    if (
                        Path.GetExtension(myFile.FileName) != ".pdf"
                        && Path.GetExtension(myFile.FileName) != ".jpg"
                        && Path.GetExtension(myFile.FileName) != ".gif"
                        && Path.GetExtension(myFile.FileName) != ".png"
                        && Path.GetExtension(myFile.FileName) != ".docx"
                        && Path.GetExtension(myFile.FileName) != ".doc"
                        && Path.GetExtension(myFile.FileName) != ".txt"
                        && Path.GetExtension(myFile.FileName) != ".xlsx"
                        && Path.GetExtension(myFile.FileName) != ".xls")
                    {
                        message = "Upload File must be one of the following file types: pdf, jpg, gif, png, docx, doc, txt, xlsx, xls.";
                    }

                    if (myFile.ContentLength > 2048 * 1024)
                    {
                        message = "Upload File can not be larger than 2MB.";
                    }
                    string content = System.Configuration.ConfigurationManager.AppSettings["UploadVendorContract"];
                    string pathForSaving = Server.MapPath(content + "/" + VendorID + "/" + SeasonID);
                    if (CreateFolderIfNeeded(pathForSaving))
                    {
                        try
                        {
                            string FileName = ValidFileName(myFile.FileName);
                            myFile.SaveAs(Path.Combine(pathForSaving, FileName));
                            isUploaded = true;
                            message = "File uploaded successfully!";
                            VenManager.UpdateVendorContractPath(Convert.ToInt32(VendorID), Convert.ToInt32(SeasonID), Path.Combine("//" + VendorID + "//" + SeasonID + "//", FileName));
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex.ToMessageAndCompleteStacktrace());
                            message = string.Format("File upload failed: {0}", ex.Message);
                        }
                    }
                }

            }
            return Json(new { isUploaded = isUploaded, message = message }, "text/html");
        }
        [Authorize]
        [HttpGet]
        public FileResult DownloadVendorContractFile(string FileName)
        {
            string content1 = "~/" + System.Configuration.ConfigurationManager.AppSettings["UploadVendorContract"] + FileName;
            string content = System.Web.Hosting.HostingEnvironment.MapPath(content1);
            try
            {
                return File(System.IO.File.ReadAllBytes(content), System.Net.Mime.MediaTypeNames.Application.Octet, Path.GetFileName(content));
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
                return null;
            }
        }
        [Authorize]
        [HttpPost]
        public ActionResult GetAreaByRegionID(int RegionID)
        {
            VenManager = new VendorManager();
            var data = VenManager.LoadArea(RegionID);
            List<System.Web.WebPages.Html.SelectListItem> AreaViewModel = new List<System.Web.WebPages.Html.SelectListItem>(); ;
            foreach (var area in data)
            {
                AreaViewModel.Add(new System.Web.WebPages.Html.SelectListItem() { Text = area.Value, Value = area.Key.ToString() });
            }
            return Json(AreaViewModel);
        }
        [Authorize]
        [HttpPost]
        public ActionResult GetRegionByCountryID(int CountryID)
        {
            VenManager = new VendorManager();
            var data = VenManager.LoadRegion(CountryID);
            List<System.Web.WebPages.Html.SelectListItem> RegionViewModel = new List<System.Web.WebPages.Html.SelectListItem>(); ;
            foreach (var reg in data)
            {
                RegionViewModel.Add(new System.Web.WebPages.Html.SelectListItem() { Text = reg.Value, Value = reg.Key.ToString() });

            }
            return Json(RegionViewModel);
        }
        [Authorize]
        [HttpPost]
        public ActionResult GetStateByCountryID(int CountryID)
        {
            VenManager = new VendorManager();
            var data = VenManager.LoadState();
            List<System.Web.WebPages.Html.SelectListItem> StateViewModel = new List<System.Web.WebPages.Html.SelectListItem>(); ;
            foreach (var state in data)
            {
                StateViewModel.Add(new System.Web.WebPages.Html.SelectListItem() { Text = state.Value, Value = state.Key });

            }
            return Json(StateViewModel);
        }
        [Authorize]
        [HttpPost]
        public ActionResult GetCityByCountryID(int CountryID, string StateID)
        {
            VenManager = new VendorManager();
            var data = VenManager.LoadCity(CountryID, StateID);
            List<System.Web.WebPages.Html.SelectListItem> CityViewModel = new List<System.Web.WebPages.Html.SelectListItem>(); ;
            foreach (var city in data)
            {
                CityViewModel.Add(new System.Web.WebPages.Html.SelectListItem() { Text = city.Value, Value = city.Key.ToString() });

            }
            return Json(CityViewModel);
        }
        [Authorize]
        public PartialViewResult AutoComplete(string PropName, string keyword)
        {
            QuotationManager QuotaManager = new QuotationManager();
            var data = QuotaManager.FindKeywordInEntity(PropName, keyword);
            AutoCompleteViewModel AutoCompVMode = new AutoCompleteViewModel() { Items = data };
            return PartialView("QuotaAutoComplete", AutoCompVMode);
        }
        #region private methods
        private ManageVendorsGridBData InitManageVendorsGridBData(ManageVendorsGridViewModel data)
        {
            ManageVendorsGridBData ManVendorsBData = new ManageVendorsGridBData();
            ManVendorsBData.Rows = new List<ManageVendorsGridRowBData>();
            foreach (var Vendor in data.Rows)
                ManVendorsBData.Rows.Add(new ManageVendorsGridRowBData
                {
                    VendorID = Vendor.VendorID,
                    Active = Vendor.IsActive,
                });
            return ManVendorsBData;
        }
        private string ValidFileName(string FileName)
        {
            return FileName.Replace("#", "_");
        }
        private bool CreateFolderIfNeeded(string path)
        {
            bool result = true;
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception ex)
                {
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                    result = false;
                }
            }
            else
            {
                try
                {
                    DirectoryInfo dir = new DirectoryInfo(path);
                    foreach (FileInfo fi in dir.GetFiles())
                    {
                        fi.IsReadOnly = false;
                        fi.Delete();
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                    result = false;
                }
            }
            return result;
        }
        private ManageVendorsGridViewModel InitManageVendorsVModel(ManageVendorsGridBData ManageVendorsData, int PageNum)
        {
            ManageVendorsGridViewModel ManVendorsVModel = new ManageVendorsGridViewModel();
            ManVendorsVModel.Rows = new List<ManageVendorsGridRowViewModel>();
            foreach (var vendor in ManageVendorsData.Rows)
                ManVendorsVModel.Rows.Add(new ManageVendorsGridRowViewModel
                {
                    VendorID = vendor.VendorID,
                    IsActive = vendor.Active == null ? false : Convert.ToBoolean(vendor.Active),
                    IsIsFind = vendor.IsFind == null ? false : Convert.ToBoolean(vendor.IsFind),
                    IsIsComp = vendor.IsComp == null ? false : Convert.ToBoolean(vendor.IsComp),
                    VendorName = vendor.VendorName,
                    City = vendor.City,
                    SelectedVendorTypeID = vendor.SelectedVendorTypeID.ToString()
                });
            if (ManVendorsVModel.Rows.Count == ManageVendorsGridBData.PageCount * PageNum)
                ManVendorsVModel.IsCanView = true;
            else
                ManVendorsVModel.IsCanView = false;
            return ManVendorsVModel;
        }
        private ManageVendorsGridViewModel InitManageVendorsSearchParams(ManageVendorsGridBData ManageVendorsData)
        {
            ManageVendorsGridViewModel ManVendorsVModel = new ManageVendorsGridViewModel();
            ManVendorsVModel.SelectedSearchVendorTypeID = "";
            ManVendorsVModel.VendorSearchTypeID = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var vti in ManageVendorsData.VendorTypeID)
                ManVendorsVModel.VendorSearchTypeID.Add(new System.Web.WebPages.Html.SelectListItem() { Text = vti.Value, Value = vti.Key.ToString() });
            ManVendorsVModel.CitySearchText = "";
            ManVendorsVModel.CitySearch = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var city in ManageVendorsData.City)
                ManVendorsVModel.CitySearch.Add(new System.Web.WebPages.Html.SelectListItem() { Text = city.Value, Value = city.Value });
            ManVendorsVModel.ActiveSearch = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var active in ManageVendorsData.Active)
                ManVendorsVModel.ActiveSearch.Add(new System.Web.WebPages.Html.SelectListItem() { Text = active.Value, Value = active.Key.ToString() });
            ManVendorsVModel.IsFindSearch = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var IsFind in ManageVendorsData.IsFind)
                ManVendorsVModel.IsFindSearch.Add(new System.Web.WebPages.Html.SelectListItem() { Text = IsFind.Value, Value = IsFind.Key.ToString() });
            ManVendorsVModel.IsCompSearch = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var IsComp in ManageVendorsData.IsComp)
                ManVendorsVModel.IsCompSearch.Add(new System.Web.WebPages.Html.SelectListItem() { Text = IsComp.Value, Value = IsComp.Key.ToString() });
            return ManVendorsVModel;
        }
        private VendorDetailsViewModel InitVendorDetailsViewModel(VendorDetailsBData data)
        {
            VendorDetailsViewModel VendorDetVModel = new VendorDetailsViewModel
            {
                VendorID = data.VendorID,
                VendorName = data.VendorName,
                Active = data.Active == null ? false : Convert.ToBoolean(data.Active),
                IsFind = data.IsFind == null ? false : Convert.ToBoolean(data.IsFind),
                IsComp = data.IsComp == null ? false : Convert.ToBoolean(data.IsComp),
                SelectedVendorTypeID = data.SelectedVendorTypeID.ToString(),
                ContactName = data.ContactName,
                ContactTitle = data.ContactTitle,
                Address = data.Address,
                SelectedCity = data.SelectedCity,
                CityID = data.CityID.ToString(),
                SelectedStateID = data.SelectedStateID,
                ArrivalDate = data.ArrivalDate != null ? Convert.ToDateTime(data.ArrivalDate).ToString("dd/MMM/yy") : "",
                Phone800 = data.Phone800,
                PhoneSales = data.PhoneSales,
                FaxSales = data.FaxSales,
                FaxNumber = data.FaxNumber,
                PhoneNumber = data.PhoneNumber,
                PostalCode = data.PostalCode,
                Preferred = data.Preferred == null ? false : Convert.ToBoolean(data.Preferred),
                Email = data.Email,
                EmailSales = data.EmailSales,
                SelectedRegionID = data.SelectedRegionID.ToString(),
                SelectedAreaID = data.SelectedAreaID.ToString(),
                SelectedCountryID = data.SelectedCountryID.ToString(),
                Notes = data.Notes,
                DepartureDate = data.DepartureDate != null ? Convert.ToDateTime(data.DepartureDate).ToString("dd/MMM/yy") : "",
            };
            VendorDetVModel.VendorTypeID = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var vti in data.VendorTypeID)
                VendorDetVModel.VendorTypeID.Add(new System.Web.WebPages.Html.SelectListItem() { Text = vti.Value, Value = vti.Key.ToString() });
            VendorDetVModel.RegionID = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var reg in data.RegionID)
                VendorDetVModel.RegionID.Add(new System.Web.WebPages.Html.SelectListItem() { Text = reg.Value, Value = reg.Key.ToString() });
            VendorDetVModel.AreaID = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var area in data.AreaID)
                VendorDetVModel.AreaID.Add(new System.Web.WebPages.Html.SelectListItem() { Text = area.Value, Value = area.Key.ToString() });
            VendorDetVModel.StateID = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var stID in data.StateID)
                VendorDetVModel.StateID.Add(new System.Web.WebPages.Html.SelectListItem() { Text = stID.Value, Value = stID.Key });
            VendorDetVModel.CountryID = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var cnt in data.CountryID)
                VendorDetVModel.CountryID.Add(new System.Web.WebPages.Html.SelectListItem() { Text = cnt.Value, Value = cnt.Key.ToString() });
            VendorDetVModel.City = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var city in data.City)
                VendorDetVModel.City.Add(new System.Web.WebPages.Html.SelectListItem() { Text = city.Value, Value = city.Key.ToString() });
            return VendorDetVModel;
        }
        private ManageVendorContractDetailsGridViewModel InitVendorContractDetailsViewModel(VendorContractsFromDetailsBData data)
        {
            ManageVendorContractDetailsGridViewModel InitContractDetails = new ManageVendorContractDetailsGridViewModel();
            InitContractDetails.Rows = new List<VendorContractDetailsViewModel>();
            foreach (var rows in data.Rows)
            {
                InitContractDetails.Rows.Add(new VendorContractDetailsViewModel()
                {
                    LineNo = rows.LineNo,
                    ServiceID = rows.ServiceID,
                    SelectedCurrency = rows.CurrencyText == "CAD" ? 2 : 1,
                    StartDate = rows.StartDate != null ? Convert.ToDateTime(rows.StartDate).ToString("dd/MMM/yy") : "",
                    EndDate = rows.EndDate != null ? Convert.ToDateTime(rows.EndDate).ToString("dd/MMM/yy") : "",
                    ProductID = rows.ProductID.ToString(),
                    Description = rows.Description,
                    Price = Convert.ToDecimal(rows.Price).ToString("F"),
                });
            }
            InitContractDetails.ContractTableDetail = new VendorContractForDetailViewModel()
            {
                ContractDate = data.ContractTableDetail.ContractDate != null ? Convert.ToDateTime(data.ContractTableDetail.ContractDate).ToString("dd/MMM/yy") : "",
                ContractStartDate = data.ContractTableDetail.ContractStartDate != null ? Convert.ToDateTime(data.ContractTableDetail.ContractStartDate).ToString("dd/MMM/yy") : "",
                ContractEndDate = data.ContractTableDetail.ContractEndDate != null ? Convert.ToDateTime(data.ContractTableDetail.ContractEndDate).ToString("dd/MMM/yy") : "",
                VendorID = data.ContractTableDetail.VendorID,
                SelectedSeasonID = data.ContractTableDetail.SelectedSeasonID,
                Note = data.ContractTableDetail.Note,
                SelectedCurrency = data.ContractTableDetail.SelectedCurrency == "CAD" ? 2 : 1,
                VendorName = data.ContractTableDetail.VendorName,
                VendorTypeCode = data.ContractTableDetail.VendorTypeCode,
                SeasonCode = data.ContractTableDetail.SeasonCode,
                SeasonDescription = data.ContractTableDetail.SeasonDescription,
                Gratuity = data.ContractTableDetail.Gratuity != null ? Convert.ToDouble(data.ContractTableDetail.Gratuity * 100).ToString("F") : "",
                Tax = data.ContractTableDetail.Tax !=null ? Convert.ToDouble(data.ContractTableDetail.Tax * 100).ToString("F"):"",
                OccTax = data.ContractTableDetail.OccTax !=null ? Convert.ToDecimal(data.ContractTableDetail.OccTax).ToString("F"):"",
                Luggage = data.ContractTableDetail.Luggage != null ? Convert.ToDecimal(data.ContractTableDetail.Luggage).ToString("F") : "",
                ContractFIle = data.ContractTableDetail.ContractFile != null ? (System.IO.File.Exists(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["UploadVendorContract"]) + data.ContractTableDetail.ContractFile) ? System.Configuration.ConfigurationManager.AppSettings["UploadVendorContract"] + data.ContractTableDetail.ContractFile : null) : null,
            };
            InitContractDetails.Services = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var Services in data.Services)
                InitContractDetails.Services.Add(new System.Web.WebPages.Html.SelectListItem() { Text = Services.Value, Value = Services.Key.ToString() });
            InitContractDetails.Currency = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var Curr in data.Currency)
                InitContractDetails.Currency.Add(new System.Web.WebPages.Html.SelectListItem() { Text = Curr.Value, Value = Curr.Key.ToString() });
            return InitContractDetails;
        }
        private ManageVendorContractsGridViewModel InitVendorContractsViewModel(VendorContractsBData data, int VendorId)
        {
            ManageVendorContractsGridViewModel InitContracts = new ManageVendorContractsGridViewModel();
            InitContracts.Row = new List<VendorContractsRowViewModel>();
            foreach (var rows in data.Rows)
            {
                InitContracts.Row.Add(new VendorContractsRowViewModel()
                {
                    ContractDate = rows.ContractDate != null ? Convert.ToDateTime(rows.ContractDate).ToString("dd/MMM/yy") : "",
                    ContractStartDate = rows.ContractStartDate != null ? Convert.ToDateTime(rows.ContractStartDate).ToString("dd/MMM/yy") : "",
                    ContractEndDate = rows.ContractEndDate != null ? Convert.ToDateTime(rows.ContractEndDate).ToString("dd/MMM/yy") : "",
                    SelectedSeasonID = rows.SelectedSeasonID.ToString(),
                    OldSelectedSeasonID = rows.SelectedSeasonID.ToString(),
                    VendorID = rows.VendorID,
                    SeasonCode = rows.SeasonCode,
                    SeasonDescription = rows.SeasonDescription,
                });
            }
            InitContracts.VendorID = VendorId;
            InitContracts.SeasonCode = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var scode in data.SeasonCode)
                InitContracts.SeasonCode.Add(new System.Web.WebPages.Html.SelectListItem() { Text = scode.Value, Value = scode.Key.ToString() });
            InitContracts.SeasonDescription = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var sdesc in data.SeasonDescription)
                InitContracts.SeasonDescription.Add(new System.Web.WebPages.Html.SelectListItem() { Text = sdesc.Value, Value = sdesc.Key.ToString() });
            return InitContracts;
        }
        private MangeVendorGroupsGridViewModel InitVendorGroupsViewModel(VendorGroupsBData data)
        {
            MangeVendorGroupsGridViewModel InitGroups = new MangeVendorGroupsGridViewModel();
            InitGroups.Rows = new List<VendorGroupsViewModel>();
            foreach (var rows in data.Rows)
            {
                InitGroups.Rows.Add(new VendorGroupsViewModel()
                {
                    VendorID = rows.VendorID,
                    GroupID = rows.GroupID,
                    ArrivalDate = rows.ArrivalDate != null ? Convert.ToDateTime(rows.ArrivalDate).ToString("dd/MMM/yy") : "",
                    DepartureDate = rows.DepartureDate != null ? Convert.ToDateTime(rows.DepartureDate).ToString("dd/MMM/yy") : "",
                    CoustomerCode = rows.CoustomerCode,
                    GroupCode = rows.GroupCode,
                    GroupName = rows.GroupName,
                    ConfirmStatusDesc = rows.ConfirmStatusDesc,
                    GroupStatusDesc = rows.GroupStatusDesc,
                    Pax = rows.Pax.ToString(),
                    Rooms = rows.Rooms.ToString(),
                });
            }
            return InitGroups;
        }
        private ManageVendorsGridBData InitSearchVendor(ManageVendorsGridViewModel Data)
        {
            ManageVendorsGridBData SrchData = new ManageVendorsGridBData
            {
                VendorName = Data.VendorNameText,
                SelectedCity = Data.CitySearchText,
                SelectedVendorTypeID = Data.SelectedSearchVendorTypeID != null ? Convert.ToInt32(Data.SelectedSearchVendorTypeID) : (int?)null,
                SelectedActive = Data.IsActiveSearch,
                SelectedIsFind = Data.IsIsFindSearch,
                SelectedIsComp = Data.IsIsCompSearch,
                PageNum = Data.PageNum,
            };
            return SrchData;
        }
        private VendorContractsBData InitVendorContractsAddBData(ManageVendorContractsGridViewModel data)
        {
            VendorContractsBData NewVendorContract = new VendorContractsBData();
            NewVendorContract.ContractDate = data.ContractDate != null ? Convert.ToDateTime(data.ContractDate) : DateTime.Now;
            NewVendorContract.ContractStartDate = data.ContractStartDate != null ? Convert.ToDateTime(data.ContractStartDate) : (DateTime?)null;
            NewVendorContract.ContractEndDate = data.ContractEndDate != null ? Convert.ToDateTime(data.ContractEndDate) : (DateTime?)null;
            NewVendorContract.VendorID = data.VendorID;
            NewVendorContract.AddContractSelectedSeasonID = Convert.ToInt32(data.AddContractSelectedSeasonID);
            return NewVendorContract;
        }
        private VendorContractsFromDetailsBData InitVendorContractDetailsAddBData(ManageVendorContractDetailsGridViewModel data)
        {
            VendorContractsFromDetailsBData NewVendorContractDetails = new VendorContractsFromDetailsBData();
            NewVendorContractDetails.Price = Convert.ToDecimal(data.Price);
            NewVendorContractDetails.ServiceID = Convert.ToInt32(data.AddContractDetailSelectedServiceID);
            NewVendorContractDetails.Description = data.Description;
            NewVendorContractDetails.CurrencyText = data.AddContractDetailSelectedCurrency == "2" ? "CAD" : "USD";
            NewVendorContractDetails.StartDate = data.StartDate != null ? Convert.ToDateTime(data.StartDate) : (DateTime?)null;
            NewVendorContractDetails.EndDate = data.EndDate != null ? Convert.ToDateTime(data.EndDate) : (DateTime?)null;
            NewVendorContractDetails.ContractTableDetail = new VendorContractForDetail()
            {
                VendorID = data.VendorID,
                SelectedSeasonID = data.SeasonID,
            };
            return NewVendorContractDetails;
        }
        private List<VendorContractsRowBData> InitVendorContractsBData(List<VendorContractsRowViewModel> data, int VendorID)
        {
            List<VendorContractsRowBData> Rows = new List<VendorContractsRowBData>();
            foreach (var row in data)
            {
                Rows.Add(new VendorContractsRowBData()
                {
                    VendorID = VendorID,
                    SelectedSeasonID = Convert.ToInt32(row.SelectedSeasonID),
                    OldSelectedSeasonID = Convert.ToInt32(row.OldSelectedSeasonID),
                    ContractDate = row.ContractDate != null ? Convert.ToDateTime(row.ContractDate) : DateTime.Now,
                    ContractStartDate = row.ContractStartDate != null ? Convert.ToDateTime(row.ContractStartDate) : (DateTime?)null,
                    ContractEndDate = row.ContractEndDate != null ? Convert.ToDateTime(row.ContractEndDate) : (DateTime?)null,
                });
            }
            return Rows;
        }
        private VendorContractsFromDetailsBData InitVendorContractDetailsBData(ManageVendorContractDetailsGridViewModel data)
        {
            VendorContractsFromDetailsBData AllVendorContractDetailsData = new VendorContractsFromDetailsBData();
            AllVendorContractDetailsData.Rows = new List<VendorContractsDetailBData>();
            if (data.Rows != null)
            {
                foreach (var row in data.Rows)
                {
                    AllVendorContractDetailsData.Rows.Add(new VendorContractsDetailBData()
                    {
                        Price = Convert.ToDecimal(row.Price),
                        ServiceID = Convert.ToInt32(row.ServiceID),
                        CurrencyText = row.SelectedCurrency == 2 ? "CAD" : "USD",
                        Description = row.Description,
                        StartDate = row.StartDate != null ? Convert.ToDateTime(row.StartDate) : (DateTime?)null,
                        EndDate = row.EndDate != null ? Convert.ToDateTime(row.EndDate) : (DateTime?)null,
                        LineNo = row.LineNo,
                    });
                }
            }
            AllVendorContractDetailsData.ContractTableDetail = new VendorContractForDetail()
            {
                VendorID = data.ContractTableDetail.VendorID,
                SelectedSeasonID = data.ContractTableDetail.SelectedSeasonID,
                ContractDate = Convert.ToDateTime(data.ContractTableDetail.ContractDate),
                ContractStartDate = data.ContractTableDetail.ContractStartDate!=null ? Convert.ToDateTime(data.ContractTableDetail.ContractStartDate) : (DateTime?)null,
                ContractEndDate = data.ContractTableDetail.ContractEndDate != null ? Convert.ToDateTime(data.ContractTableDetail.ContractEndDate) : (DateTime?)null,
                Note = data.ContractTableDetail.Note,
                SelectedCurrency=data.ContractTableDetail.SelectedCurrency == 2 ? "CAD" : "USD",
                Luggage = data.ContractTableDetail != null ? Convert.ToDecimal(data.ContractTableDetail.Luggage) : (decimal?)null,
                Tax = data.ContractTableDetail.Tax != null ? Convert.ToDouble(data.ContractTableDetail.Tax) / 100 : (double?)null,
                OccTax = data.ContractTableDetail.OccTax != null ? Convert.ToDecimal(data.ContractTableDetail.OccTax) : (decimal?)null,
                Gratuity = data.ContractTableDetail.Gratuity != null ? Convert.ToDouble(data.ContractTableDetail.Gratuity) / 100 : (double?)null,
            };
            return AllVendorContractDetailsData;
        }
        private VendorDetailsBData InitVendorDetailsBData(VendorDetailsViewModel data)
        {
            VendorDetailsBData VendorBData = new VendorDetailsBData
            {
                VendorID = data.VendorID,
                VendorName = data.VendorName,
                SelectedVendorTypeID = data.SelectedVendorTypeID != null ? Convert.ToInt32(data.SelectedVendorTypeID) : (int?)null,
                ContactName = data.ContactName,
                ContactTitle = data.ContactTitle,
                Address = data.Address,
                SelectedCity = data.SelectedCity,
                CityID = (data.CityID != null && data.CityID != "0") ? Convert.ToInt32(data.CityID) : (int?)null,
                SelectedStateID = data.SelectedCountryID == "1" ? (data.SelectedStateID == "0" ? null : data.SelectedStateID) : null,
                ArrivalDate = data.ArrivalDate != null ? Convert.ToDateTime(data.ArrivalDate) : (DateTime?)null,
                Phone800 = data.Phone800,
                PostalCode = data.PostalCode,
                Active = data.Active,
                IsFind = data.IsFind,
                IsComp = data.IsComp,
                Preferred = data.Preferred,
                PhoneNumber = data.PhoneNumber,
                Email = data.Email,
                EmailSales = data.EmailSales,
                PhoneSales = data.PhoneSales,
                SelectedRegionID = data.SelectedRegionID != null ? Convert.ToInt16(data.SelectedRegionID) : (short?)null,
                FaxNumber = data.FaxNumber,
                FaxSales = data.FaxSales,
                SelectedAreaID = data.SelectedAreaID != null ? Convert.ToInt32(data.SelectedAreaID) : (int?)null,
                SelectedCountryID = data.SelectedCountryID != null ? Convert.ToInt32(data.SelectedCountryID) : (int?)null,
                Notes = data.Notes,
                DepartureDate = data.DepartureDate != null ? Convert.ToDateTime(data.DepartureDate) : (DateTime?)null,
            };
            return VendorBData;
        }
        #endregion
    }
}